// 全局变量
let monitoringActive = true;
let refreshInterval; // 定时刷新句柄
let scanInterval = 10; // 扫描间隔（秒）

// 页面加载完成后初始化
window.addEventListener('pywebviewready', function() {
    loadPoints();
    
    // 绑定事件
    document.getElementById('addPointBtn').addEventListener('click', showAddPointModal);
    document.getElementById('toggleMonitoringBtn').addEventListener('click', toggleMonitoring);
    document.getElementById('refreshBtn').addEventListener('click', loadPoints);
    document.getElementById('savePointBtn').addEventListener('click', savePoint);
    document.getElementById('confirmDeleteBtn').addEventListener('click', deletePoint);
    document.getElementById('updateIntervalBtn').addEventListener('click', updateScanInterval);
    
    // 主题切换按钮
    document.getElementById('lightThemeBtn').addEventListener('click', function() {
        document.body.classList.remove('dark-theme');
        document.body.classList.add('light-theme');
    });
    
    document.getElementById('darkThemeBtn').addEventListener('click', function() {
        document.body.classList.remove('light-theme');
        document.body.classList.add('dark-theme');
    });
    
    // 设置定时刷新（根据扫描间隔）
    refreshInterval = setInterval(loadPoints, scanInterval * 1000);
    
    // 页面加载完成后自动启动监控
    if (typeof pywebview !== 'undefined' && typeof pywebview.api !== 'undefined') {
        pywebview.api.start_monitoring().catch(function(error) {
            console.error('自动启动监控出错:', error);
        });
    }
});

// 页面关闭时清理定时器
window.addEventListener('beforeunload', function() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
});

// 更新扫描间隔
function updateScanInterval() {
    const newInterval = parseInt(document.getElementById('intervalInput').value);
    if (isNaN(newInterval) || newInterval < 1 || newInterval > 3600) {
        showNotification('请输入1-3600之间的有效数字', 'error');
        return;
    }
    
    // 调用后端API更新扫描间隔
    if (typeof pywebview !== 'undefined' && typeof pywebview.api !== 'undefined') {
        pywebview.api.update_scan_interval({
            interval: newInterval
        }).then(function(result) {
            if (result) {
                scanInterval = newInterval;
                
                // 重新设置定时刷新
                if (refreshInterval) {
                    clearInterval(refreshInterval);
                }
                refreshInterval = setInterval(loadPoints, scanInterval * 1000);
                
                showNotification(`扫描间隔已更新为 ${scanInterval} 秒`, 'success');
            } else {
                showNotification('更新扫描间隔失败', 'error');
            }
        }).catch(function(error) {
            console.error('更新扫描间隔出错:', error);
            showNotification('更新扫描间隔失败: ' + error, 'error');
        });
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.getElementById('notification');
    notification.textContent = message;
    notification.style.display = 'block';
    notification.style.borderLeftColor = type === 'success' ? '#198754' : 
                                        type === 'error' ? '#dc3545' : '#0d6efd';
    
    setTimeout(() => {
        notification.style.display = 'none';
    }, 3000);
}

// 加载所有点位
function loadPoints() {
    if (typeof pywebview !== 'undefined' && typeof pywebview.api !== 'undefined') {
        pywebview.api.get_all_points().then(function(points) {
            const tbody = document.getElementById('pointsTableBody');
            tbody.innerHTML = '';
            
            points.forEach(function(point) {
                const row = document.createElement('tr');
                if (point[4] === 0) { // 如果禁用
                    row.classList.add('point-disabled');
                }
                
                // 根据新的数据结构，点位信息包含：
                // 0:id, 1:name, 2:url, 3:node_id, 4:enabled, 5:status, 6:last_check
                const status = point[5] || 'unknown';
                const lastCheck = point[6] || 'N/A';
                
                // 状态样式
                let statusClass = 'status-unknown';
                let statusText = '未知';
                if (status === 'connected') {
                    statusClass = 'status-connected';
                    statusText = '已连接';
                } else if (status === 'disconnected') {
                    statusClass = 'status-disconnected';
                    statusText = '未连接';
                }
                
                row.innerHTML = `
                    <td>${point[0]}</td>
                    <td>${point[1]}</td>
                    <td>${point[2]}</td>
                    <td>${point[3]}</td>
                    <td>
                        <span class="status-indicator ${statusClass}"></span>
                        ${statusText}
                    </td>
                    <td>${lastCheck}</td>
                    <td>
                        <span class="badge ${point[4] ? 'bg-success' : 'bg-secondary'}">
                            ${point[4] ? '启用' : '禁用'}
                        </span>
                    </td>
                    <td>
                        <div class="btn-group btn-group-sm" role="group">
                            <button class="btn btn-outline-primary edit-btn" data-id="${point[0]}">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-outline-danger delete-btn" data-id="${point[0]}" data-name="${point[1]}">
                                <i class="fas fa-trash"></i>
                            </button>
                            <button class="btn btn-outline-${point[4] ? 'warning' : 'success'} toggle-btn" data-id="${point[0]}">
                                <i class="fas fa-${point[4] ? 'pause' : 'play'}"></i>
                            </button>
                        </div>
                    </td>
                `;
                tbody.appendChild(row);
            });
            
            // 绑定编辑、删除和切换按钮事件
            document.querySelectorAll('.edit-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const id = this.getAttribute('data-id');
                    showEditPointModal(id);
                });
            });
            
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const id = this.getAttribute('data-id');
                    const name = this.getAttribute('data-name');
                    showDeleteConfirmation(id, name);
                });
            });
            
            document.querySelectorAll('.toggle-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const id = this.getAttribute('data-id');
                    togglePointStatus(id);
                });
            });
        }).catch(function(error) {
            console.error('加载点位出错:', error);
        });
    }
}

// 显示新增点位模态框
function showAddPointModal() {
    document.getElementById('pointModalLabel').textContent = '新增点位';
    document.getElementById('pointForm').reset();
    document.getElementById('pointId').value = '';
    new bootstrap.Modal(document.getElementById('pointModal')).show();
}

// 显示编辑点位模态框
function showEditPointModal(id) {
    if (typeof pywebview !== 'undefined' && typeof pywebview.api !== 'undefined') {
        pywebview.api.get_point_by_id({point_id: parseInt(id)}).then(function(point) {
            if (point) {
                document.getElementById('pointModalLabel').textContent = '编辑点位';
                document.getElementById('pointId').value = point[0];
                document.getElementById('pointName').value = point[1];
                document.getElementById('pointUrl').value = point[2];
                document.getElementById('pointNodeId').value = point[3];
                new bootstrap.Modal(document.getElementById('pointModal')).show();
            }
        }).catch(function(error) {
            console.error('获取点位信息出错:', error);
            showNotification('获取点位信息失败: ' + error, 'error');
        });
    }
}

// 保存点位
function savePoint() {
    if (typeof pywebview === 'undefined') {
        console.log('pywebview is not defined');
        return;
    }
    
    if (typeof pywebview.api === 'undefined') {
        console.log('pywebview.api is not defined');
        return;
    }
    
    console.log('Available API methods:', pywebview.api);
    
    const id = document.getElementById('pointId').value;
    const name = document.getElementById('pointName').value;
    const url = document.getElementById('pointUrl').value;
    const nodeId = document.getElementById('pointNodeId').value;
    
    if (!name || !url || !nodeId) {
        showNotification('请填写所有字段', 'error');
        return;
    }
    
    if (id) {
        // 更新现有点位
        pywebview.api.update_point({
            point_id: parseInt(id),
            name: name,
            url: url,
            node_id: nodeId
        }).then(function(result) {
            if (result) {
                bootstrap.Modal.getInstance(document.getElementById('pointModal')).hide();
                loadPoints();
                showNotification('点位更新成功', 'success');
            } else {
                showNotification('更新失败', 'error');
            }
        }).catch(function(error) {
            console.error('更新点位出错:', error);
            showNotification('更新失败: ' + error, 'error');
        });
    } else {
        // 新增点位
        pywebview.api.add_point({
            name: name,
            url: url,
            node_id: nodeId
        }).then(function(result) {
            if (result) {
                bootstrap.Modal.getInstance(document.getElementById('pointModal')).hide();
                loadPoints();
                showNotification('点位添加成功', 'success');
            } else {
                showNotification('新增失败', 'error');
            }
        }).catch(function(error) {
            console.error('新增点位出错:', error);
            showNotification('新增失败: ' + error, 'error');
        });
    }
}

// 显示删除确认对话框
function showDeleteConfirmation(id, name) {
    document.getElementById('deletePointId').value = id;
    new bootstrap.Modal(document.getElementById('deleteModal')).show();
}

// 删除点位
function deletePoint() {
    if (typeof pywebview === 'undefined' || typeof pywebview.api === 'undefined') return;
    
    const id = document.getElementById('deletePointId').value;
    pywebview.api.delete_point({point_id: parseInt(id)}).then(function(result) {
        if (result) {
            bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
            loadPoints();
            showNotification('点位删除成功', 'success');
        } else {
            showNotification('删除失败', 'error');
        }
    }).catch(function(error) {
        console.error('删除点位出错:', error);
        showNotification('删除失败: ' + error, 'error');
    });
}

// 切换点位状态（启用/禁用）
function togglePointStatus(id) {
    if (typeof pywebview === 'undefined' || typeof pywebview.api === 'undefined') return;
    
    pywebview.api.toggle_point_status({point_id: parseInt(id)}).then(function(result) {
        if (result) {
            loadPoints();
            showNotification('点位状态已切换', 'success');
        } else {
            showNotification('状态切换失败', 'error');
        }
    }).catch(function(error) {
        console.error('切换点位状态出错:', error);
        showNotification('状态切换失败: ' + error, 'error');
    });
}

// 切换监控状态
function toggleMonitoring() {
    if (typeof pywebview === 'undefined' || typeof pywebview.api === 'undefined') return;
    
    monitoringActive = !monitoringActive;
    const btn = document.getElementById('toggleMonitoringBtn');
    const statusLabel = document.getElementById('statusLabel');
    
    if (monitoringActive) {
        btn.innerHTML = '<i class="fas fa-pause me-1"></i>暂停监控';
        btn.classList.remove('btn-success');
        btn.classList.add('btn-warning');
        statusLabel.textContent = '运行中';
        statusLabel.classList.remove('bg-secondary');
        statusLabel.classList.add('bg-success');
        pywebview.api.start_monitoring().catch(function(error) {
            console.error('启动监控出错:', error);
            showNotification('启动监控失败: ' + error, 'error');
        });
    } else {
        btn.innerHTML = '<i class="fas fa-play me-1"></i>继续监控';
        btn.classList.remove('btn-warning');
        btn.classList.add('btn-success');
        statusLabel.textContent = '已暂停';
        statusLabel.classList.remove('bg-success');
        statusLabel.classList.add('bg-secondary');
        pywebview.api.stop_monitoring().catch(function(error) {
            console.error('停止监控出错:', error);
            showNotification('停止监控失败: ' + error, 'error');
        });
    }
    
    // 无论启动还是停止监控，都重新加载点位信息
    loadPoints();
}